import router from '@system.router'
import prompt from '@system.prompt'
import storage from '@system.storage'

export default {
  data: {
    caseId: 0,
    evidence: [],
    contradictions: [],
    analysisResults: [],
    timeline: [],
    connections: [],
    selectedEvidence: null,
    analysisMode: 'overview'
  },

  onInit() {
    const params = router.getParams()
    this.caseId = params.caseId
    this.evidence = params.evidence || []
    this.contradictions = params.contradictions || []
    this.analyzeEvidence()
    this.buildTimeline()
    this.findConnections()
  },

  analyzeEvidence() {
    // 分析证据的重要性和可信度
    this.analysisResults = this.evidence.map((item, index) => {
      const importance = this.calculateImportance(item)
      const credibility = this.calculateCredibility(item)
      const relevance = this.calculateRelevance(item)
      
      return {
        id: index,
        content: item,
        importance: importance,
        credibility: credibility,
        relevance: relevance,
        overallScore: (importance + credibility + relevance) / 3,
        category: this.categorizeEvidence(item),
        timestamp: this.generateTimestamp(),
        source: this.determineSource(item)
      }
    })
    
    // 按重要性排序
    this.analysisResults.sort((a, b) => b.overallScore - a.overallScore)
  },

  calculateImportance(evidence) {
    // 根据证据内容计算重要性
    const importantKeywords = ['犯罪', '威胁', '秘密', '金钱', '仇恨', '报复', '谋杀', '死亡']
    const score = importantKeywords.reduce((score, keyword) => {
      return evidence.includes(keyword) ? score + 0.2 : score
    }, 0.3)
    
    return Math.min(1, score)
  },

  calculateCredibility(evidence) {
    // 根据证据来源和性质计算可信度
    let credibility = 0.5
    
    if (evidence.includes('承认') || evidence.includes('坦白')) {
      credibility += 0.3
    }
    if (evidence.includes('监控') || evidence.includes('记录')) {
      credibility += 0.2
    }
    if (evidence.includes('可能') || evidence.includes('大概')) {
      credibility -= 0.2
    }
    
    return Math.max(0, Math.min(1, credibility))
  },

  calculateRelevance(evidence) {
    // 计算证据与案件的相关性
    const caseKeywords = ['受害者', '嫌疑人', '时间', '地点', '动机', '手法']
    const score = caseKeywords.reduce((score, keyword) => {
      return evidence.includes(keyword) ? score + 0.15 : score
    }, 0.2)
    
    return Math.min(1, score)
  },

  categorizeEvidence(evidence) {
    // 分类证据
    if (evidence.includes('不在场') || evidence.includes('时间')) {
      return 'alibi'
    } else if (evidence.includes('关系') || evidence.includes('认识')) {
      return 'relationship'
    } else if (evidence.includes('动机') || evidence.includes('仇恨')) {
      return 'motive'
    } else if (evidence.includes('秘密') || evidence.includes('隐瞒')) {
      return 'secret'
    } else {
      return 'general'
    }
  },

  determineSource(evidence) {
    // 确定证据来源
    if (evidence.includes('承认') || evidence.includes('坦白')) {
      return 'confession'
    } else if (evidence.includes('监控')) {
      return 'surveillance'
    } else if (evidence.includes('证人')) {
      return 'witness'
    } else {
      return 'investigation'
    }
  },

  buildTimeline() {
    // 构建时间线
    this.timeline = [
      {
        time: '18:00',
        event: '受害者最后一次被看到',
        importance: 0.9,
        evidence: ['监控录像', '目击证人']
      },
      {
        time: '19:30',
        event: '嫌疑人A出现在现场附近',
        importance: 0.7,
        evidence: ['手机定位', '监控录像']
      },
      {
        time: '20:15',
        event: '受害者手机关机',
        importance: 0.8,
        evidence: ['通讯记录']
      },
      {
        time: '21:00',
        event: '嫌疑人B声称在家',
        importance: 0.6,
        evidence: ['嫌疑人陈述']
      },
      {
        time: '22:30',
        event: '受害者被发现死亡',
        importance: 1.0,
        evidence: ['现场勘查', '法医报告']
      }
    ]
  },

  findConnections() {
    // 寻找证据间的关联
    this.connections = []
    
    for (let i = 0; i < this.analysisResults.length; i++) {
      for (let j = i + 1; j < this.analysisResults.length; j++) {
        const connection = this.findConnectionBetween(
          this.analysisResults[i],
          this.analysisResults[j]
        )
        if (connection) {
          this.connections.push(connection)
        }
      }
    }
  },

  findConnectionBetween(evidence1, evidence2) {
    // 寻找两个证据之间的关联
    const commonKeywords = this.findCommonKeywords(evidence1.content, evidence2.content)
    const temporalConnection = this.checkTemporalConnection(evidence1, evidence2)
    const logicalConnection = this.checkLogicalConnection(evidence1, evidence2)
    
    if (commonKeywords.length > 0 || temporalConnection || logicalConnection) {
      return {
        evidence1: evidence1,
        evidence2: evidence2,
        connectionType: this.determineConnectionType(commonKeywords, temporalConnection, logicalConnection),
        strength: this.calculateConnectionStrength(commonKeywords, temporalConnection, logicalConnection),
        description: this.generateConnectionDescription(commonKeywords, temporalConnection, logicalConnection)
      }
    }
    
    return null
  },

  findCommonKeywords(content1, content2) {
    const words1 = content1.split(' ')
    const words2 = content2.split(' ')
    return words1.filter(word => words2.includes(word) && word.length > 2)
  },

  checkTemporalConnection(evidence1, evidence2) {
    // 检查时间关联
    return Math.abs(evidence1.timestamp - evidence2.timestamp) < 3600000 // 1小时内
  },

  checkLogicalConnection(evidence1, evidence2) {
    // 检查逻辑关联
    return evidence1.category === evidence2.category && evidence1.source !== evidence2.source
  },

  determineConnectionType(commonKeywords, temporalConnection, logicalConnection) {
    if (commonKeywords.length > 0) return 'keyword'
    if (temporalConnection) return 'temporal'
    if (logicalConnection) return 'logical'
    return 'unknown'
  },

  calculateConnectionStrength(commonKeywords, temporalConnection, logicalConnection) {
    let strength = 0
    if (commonKeywords.length > 0) strength += Math.min(0.5, commonKeywords.length * 0.1)
    if (temporalConnection) strength += 0.3
    if (logicalConnection) strength += 0.2
    return Math.min(1, strength)
  },

  generateConnectionDescription(commonKeywords, temporalConnection, logicalConnection) {
    if (commonKeywords.length > 0) {
      return `两份证据都提到了"${commonKeywords[0]}"`
    }
    if (temporalConnection) {
      return '两份证据在时间上有密切联系'
    }
    if (logicalConnection) {
      return '两份证据在逻辑上相互支持'
    }
    return '两份证据存在关联'
  },

  selectEvidenceItem(evidence) {
    this.selectedEvidence = evidence
    this.analysisMode = 'detail'
  },

  generateTimestamp() {
    return Date.now() - Math.floor(Math.random() * 86400000) // 过去24小时内
  },

  showContradictionAnalysis() {
    this.analysisMode = 'contradictions'
  },

  showTimelineAnalysis() {
    this.analysisMode = 'timeline'
  },

  showConnectionAnalysis() {
    this.analysisMode = 'connections'
  },

  generateReport() {
    // 生成证据分析报告
    const report = {
      totalEvidence: this.evidence.length,
      highImportanceEvidence: this.analysisResults.filter(e => e.importance > 0.7).length,
      contradictionsFound: this.contradictions.length,
      connectionsFound: this.connections.length,
      timelineCompleteness: this.calculateTimelineCompleteness(),
      keyFindings: this.generateKeyFindings(),
      recommendations: this.generateRecommendations()
    }
    
    storage.set({
      key: 'evidenceReport_' + this.caseId,
      value: JSON.stringify(report)
    })
    
    prompt.showDialog({
      title: '证据分析报告',
      message: this.formatReport(report),
      buttons: [
        { text: '查看详细报告', color: '#1976d2' },
        { text: '关闭', color: '#666666' }
      ],
      success: (result) => {
        if (result.index === 0) {
          this.showDetailedReport(report)
        }
      }
    })
  },

  calculateTimelineCompleteness() {
    // 计算时间线完整性
    const expectedEvents = 10 // 预期事件数量
    return Math.min(1, this.timeline.length / expectedEvents)
  },

  generateKeyFindings() {
    // 生成关键发现
    const findings = []
    
    // 检查高重要性证据
    const highImportance = this.analysisResults.filter(e => e.importance > 0.8)
    if (highImportance.length > 0) {
      findings.push(`发现${highImportance.length}个高重要性证据`)
    }
    
    // 检查矛盾
    if (this.contradictions.length > 0) {
      findings.push(`发现${this.contradictions.length}个矛盾点`)
    }
    
    // 检查强关联
    const strongConnections = this.connections.filter(c => c.strength > 0.7)
    if (strongConnections.length > 0) {
      findings.push(`发现${strongConnections.length}个强关联证据`)
    }
    
    return findings
  },

  generateRecommendations() {
    // 生成建议
    const recommendations = []
    
    if (this.contradictions.length > 2) {
      recommendations.push('重点关注矛盾点，可能需要重新审讯相关嫌疑人')
    }
    
    if (this.timeline.length < 5) {
      recommendations.push('时间线信息不足，需要收集更多时间相关证据')
    }
    
    const lowCredibility = this.analysisResults.filter(e => e.credibility < 0.5)
    if (lowCredibility.length > 0) {
      recommendations.push('部分证据可信度较低，需要验证')
    }
    
    return recommendations
  },

  formatReport(report) {
    return `证据分析完成！\n\n` +
           `总证据数: ${report.totalEvidence}\n` +
           `高重要性证据: ${report.highImportanceEvidence}\n` +
           `发现矛盾: ${report.contradictionsFound}\n` +
           `证据关联: ${report.connectionsFound}\n` +
           `时间线完整性: ${(report.timelineCompleteness * 100).toFixed(1)}%`
  },

  showDetailedReport(report) {
    router.push({
      uri: 'pages/evidenceReport/evidenceReport',
      params: { report: report }
    })
  },

  exportEvidence() {
    // 导出证据数据
    const exportData = {
      caseId: this.caseId,
      timestamp: new Date().toISOString(),
      evidence: this.analysisResults,
      contradictions: this.contradictions,
      timeline: this.timeline,
      connections: this.connections
    }
    
    // 保存到本地存储
    storage.set({
      key: 'evidenceExport_' + Date.now(),
      value: JSON.stringify(exportData)
    })
    
    prompt.showToast({
      message: '证据数据已导出',
      duration: 2000
    })
  },

  updateQuestion(event) {
    this.currentQuestion = event.value
  }
}